<template>
    <div>
      <div>
        <button @click="getLoc()">获取位置信息</button>
      </div>
      <div id="map"></div>
    </div>
</template>
<script>
export default {
  data() {
    return {
      map: "",
      list: [], //存放矩形点数据
      rectgroup: "", //矩形图层
      cirgroup: "", //点图层
      markerlist: [], //点名称
      testgroup: "", //移动时绘制矩形图形的图层
      pointMarkerList: [], // 保存点位的数组变量
      lineList: [], // 线的变量
      polygonList: [], // // 存储画的多边形
      iconList: [],
      annoList: [],
      regionList: [] // 腰子
    };
  },
  mounted() {
    // this.loadMap();
    this.initLeaflet();
  },
  methods: {
    loadMap() {
      map = L.map("map");
      L.tileLayer(
        "https://gac-geo.googlecnapps.cn/maps/vt?lyrs=s,m&gl=CN&x={x}&y={y}&z={z}",
        {
          maxZoom: 13,
          minZoom: 7,
          attribution: "谷歌地图",
          subdomains: ["1", "2", "3", "4"],
          center: [39.7 ,117.4],
          zoom: 6,
          zoomControl: true, //禁用 + - 按钮
          doubleClickZoom: true, // 禁用双击放大
          attributionControl: false, // 移除右下角leaflet标识
          dragging: true, //禁止鼠标拖动滚动
          boxZoom: true, //决定地图是否可被缩放到鼠标拖拽出的矩形的视图，鼠标拖拽时需要同时按住shift键.
          scrollWheelZoom: true //禁止鼠标滚动缩放
        }
      ).addTo(map);
      map.setView([40.35, 117.36], 7);
    },
    initLeaflet(level) {
      if (this.map) {
        this.map.remove();
      }
      this.map = this.initLeafletMap("grid_map");
      //添加左侧绘制控件
      this.map.pm.addControls({
        position: "topleft",
        drawMarker: false, // 绘制标记
        drawCircle: false, // 绘制圆形
        drawPolyline: false, // 绘制折线
        drawRectangle: false, // 绘制矩形
        drawPolygon: true, // only五级网格绘制
        drawCircleMarker: false, // 绘制圆形标记
        removalMode: false, // 清除图层
        cutPolygon: false, // 删除图层里的部分内容
        editMode: false, // 编辑多边形
        dragMode: false // 拖动多边形
      });

      let that = this;

      //绘制开始事件
      this.map.on("pm:drawstart", e => {
        if (e.shape === "Marker") {
          document.getElementById("grid_map").style.cursor = "none";
        } else {
          document.getElementById("grid_map").style.cursor = "grab";
        }
      });

      //绘制模式关闭
      this.map.on("pm:drawend", () => {
        document.getElementById("grid_map").style.cursor = "grab";
      });

      //绘制完成事件
      this.map.on("pm:create", e => {
        let shape = e.shape;
        //多边形
        if ("Polygon" === shape || "Rectangle" === shape) {
          // 处理绘制完成的逻辑
        }
      });

      //移除事件
      this.map.on("pm:remove", () => {
        let layers = that.map.pm.getGeomanLayers();
        if (layers) {
          for (let i = 0; i < layers.length; i++) {
            //多边形
            if (
              layers[i].pm._shape === "Polygon" ||
              layers[i].pm._shape === "Rectangle"
            ) {
              // 经纬度
              // layers[i]._latlngs[0]
            }
          }
        }
      });
      //地图缩放事件
      this.map.on("zoomend", () => {});

      // 双击事件
      this.map.addEventListener("dblclick", function() {});
      // 拖拽事件
      this.map.addEventListener("dragend", function() {});
      // 缩放事件
      this.map.addEventListener("zoomend", function() {});

      // 先清除all多边形
      this.clearAllPolygon(this.map);
    },
    // 初始化map
    initLeafletMap(id, zoom = 16) {
      let normalMap = window.L.tileLayer.chinaProvider("Baidu.Normal.Map", {
        maxZoom: 18,
        minZoom: 10
      });
      // let normalMap = L.tileLayer(
      //     "https://gac-geo.googlecnapps.cn/maps/vt?lyrs=s,m&gl=CN&x={x}&y={y}&z={z}",
      //     {
      //       maxZoom: 18,
      //       minZoom: 10,
      //       attribution: "谷歌地图",
      //       subdomains: ["1", "2", "3", "4"],
      //       center: [39.125596, 117.190182],
      //       zoom: 6,
      //       zoomControl: true, //禁用 + - 按钮
      //       doubleClickZoom: true, // 禁用双击放大
      //       attributionControl: false, // 移除右下角leaflet标识
      //       dragging: true, //禁止鼠标拖动滚动
      //       boxZoom: true, //决定地图是否可被缩放到鼠标拖拽出的矩形的视图，鼠标拖拽时需要同时按住shift键.
      //       scrollWheelZoom: true //禁止鼠标滚动缩放
      //     }
      //   ).addTo(map);
      //   map.setView([40.35, 117.36], 7);
      let normal = window.L.layerGroup([normalMap]);
      let map = window.L.map(id, {
        crs: window.L.CRS.Baidu,
        center: [36.717672, 119.160414],
        zoom: zoom,
        layers: [normal],
        zoomControl: true,
        trackResize: true
      });
      //初始化绘制插件
      window.L.PM.initialize();
      //中文
      map.pm.setLang("zh");

      // 比例尺
      window.L.control
        .scale({ maxWidth: 200, metric: true, imperial: false })
        .addTo(map);
      return map;
    },

    // 清除所有多边形
    clearAllPolygon(map) {
      let layers = map.pm.getGeomanLayers();
      if (layers) {
        layers.forEach(res => {
          map.removeLayer(res);
        });
      }
    },
    polygonToMap(list) {
      // 已选中图标
      let PickedIcon = window.L.Icon.extend({
        options: {
          iconUrl: require("@/assets/logo/logo.png"),
          iconSize: [24, 24]
        }
      });
      // 可编辑图标
      let EditIcon = window.L.Icon.extend({
        options: {
          iconUrl: require("@/assets/logo/logo.png"),
          iconSize: [24, 24]
        }
      });
      // 清除all marker
      for (let i = 0; i < this.selectMarkers.length; i++) {
        this.map.removeLayer(this.selectMarkers[i].marker);
      }
      this.selectMarkers = [];
      list.forEach(res => {
        let latlngs = [];
        let rangePoints = res.rangePoints;
        let options = {
          color: "#5b8ff9", // res.color
          fillColor: "#5b8ff9", // res.color
          fillOpacity: 0.1,
          data: res
        };
        rangePoints.forEach(item => {
          latlngs.push([item.lat, item.lng]);
        });
        // 绘制多边形
        let polygonLayer = window.L.polygon(latlngs, options).addTo(this.map);
        // 点击事件
        this.polygonInit(polygonLayer);
        // 绘制覆盖点
        let isPicked = res.isPicked;
        let isEdit = res.isEdit;
        if (isPicked === 1 || isEdit === 1) {
          // 已选中/可编辑
          new window.L.marker([res.latitude, res.longitude], {
            icon: res.isEdit ? new EditIcon() : new PickedIcon(),
            data: res
          })
            .addTo(this.map)
            .on("click", () => {
              if (isEdit === 1) {
                // 编辑
                this.currentGridData = res;
                // 禁用全局编辑按钮
                this.map.pm.disableGlobalEditMode();
                this.editMapLayer(polygonLayer);
              }
            });
        }
        // map 改变后，重新设置map选中的marker
        if (this.gridData.gridIdList.indexOf(res.id) > -1) {
          let marker = new window.L.marker([res.latitude, res.longitude], {
            icon: new PickedIcon()
          })
            .addTo(this.map)
            .on("click", () => {
              if (this.gridData.gridLevel < 5) {
                // 五级以下可选
                let index = this.gridData.gridIdList.indexOf(res.id);
                if (index > -1) {
                  this.gridData.gridIdList.splice(index, 1);
                  this.gridDataList.splice(index, 1);
                  this.selectMarkers.splice(index, 1);
                }
                this.map.removeLayer(marker);
              }
            });
          this.selectMarkers.push({
            marker: marker,
            id: res.id
          });
        }
        // 绘制文字
        let iconLabel = window.L.divIcon({
          html: res.gridName,
          className: "my-grid-configure-icon",
          iconSize: 30,
          data: res
        });
        new window.L.marker([res.latitude, res.longitude], {
          icon: iconLabel
        })
          .addTo(this.map)
          .on("click", () => {
            if (res.isEdit === 1) {
              // 可编辑
              this.currentGridData = res;
              // 禁用全局编辑按钮
              this.map.pm.disableGlobalEditMode();
              this.editMapLayer(polygonLayer);
            }
          });
      });
    },

    // 多边形需要执行的操作
    polygonInit(polygonLayer) {
      //点击事件
      polygonLayer.on("click", e => {
        if (
          e.sourceTarget.options.data &&
          e.sourceTarget.options.data.isEdit === 1
        ) {
          // 可编辑
          this.currentGridData = e.sourceTarget.options.data;
          // 禁用全局编辑按钮
          this.map.pm.disableGlobalEditMode();
          this.editMapLayer(polygonLayer);
          return;
        }

        if (e.sourceTarget.options.data) {
          this.polygonSelectHandler(e.sourceTarget.options.data);
        }
      });
    },
    editMapLayer(layer) {
      layer.pm.enable({
        allowSelfIntersection: true,
        preventMarkerRemoval: false // 禁止右键删除点
      });
      let that = this;
      // 监听编辑事件
      layer.on("pm:edit", e => {
        // 拖动后的坐标
        that.currentGridData.rangePoints = e.target._latlngs[0];
      });
      layer.on("pm:vertexadded", e => {
        // 添加顶点
        console.log(e, "添加顶点");
      });
    }
  }
};
</script>
